//
//  YCL_Common.m
//  Lottery
//
//  Created by 李宗帅 on 2017/6/1.
//  Copyright © 2017年 Aesthetic92. All rights reserved.
//

#import "LTX_Common.h"
#import "AppDelegate.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "sys/utsname.h"
#import <AudioToolbox/AudioToolbox.h>


@implementation LTX_Common


+(void) showAlertWithMessage:(NSString*)_mes
{
    [[self class]showAlertWithMessageup:_mes];
}


+ (void)showAlertWithMessage:(NSString *)_mes offset:(UIOffset)offset {
    
    AppDelegate * deleta =(AppDelegate*)[UIApplication sharedApplication].delegate;
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:deleta.window animated:YES];
    CGSize size = [self sizeFitForContent:_mes withSize:CGSizeMake(ScreenW, 20) withFont:[UIFont systemFontOfSize:16]];
    float textWidth = size.width;
    float textHeight = size.height;
    hud.bezelView.color = JSRGBColorWithAlpha(0, 0, 0, 0.5);
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.contentColor = [UIColor whiteColor];
    //add by zsl 垂直居中显示
    hud.offset = CGPointMake(hud.offset.x, -textHeight/2 - offset.vertical);
    hud.offset = CGPointMake(offset.horizontal, hud.offset.y);
    
    if(textWidth > ScreenW-40)
        hud.detailsLabel.text = _mes;
    else
        hud.label.text = _mes;
    
    hud.mode = MBProgressHUDModeText;
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    hud.userInteractionEnabled = NO;
    [hud hideAnimated:YES afterDelay:2.0];
}


+ (void)showAnimationWithView:(UIView *)view
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.bezelView.color = JSRGBColorWithAlpha(0, 0, 0, 0.5);
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.contentColor = [UIColor whiteColor];
}

+ (void)showAlertWithTitle:(NSString *)title msg:(NSString *)msg actions:(NSArray *)actions viewController:(UIViewController *)vc callBack:(void(^)(NSString *title))clickAction;
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title.length?title:nil message:msg.length?msg:nil preferredStyle:UIAlertControllerStyleAlert];
    
    for (NSString *actionTitle in actions) {
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            clickAction(action.title);
        }];
        [alert addAction:action];
    }
    [vc presentViewController:alert animated:YES completion:nil];
}

/**
 *  提示框（提示框垂直居中显示）
 * @param _mes 提示内容
 */
+(void) showAlertWithMessageup:(NSString*)_mes
{
    [self showAlertWithMessage:_mes offset:UIOffsetZero];
}


+ (NSMutableAttributedString*)getUnderlineTextWithTextColor:(UIColor *)color lineColor:(UIColor *)lineColor text:(NSString *)text
{
    NSMutableAttributedString* tncString = [[NSMutableAttributedString alloc] initWithString:text];
    
    [tncString addAttribute:NSUnderlineStyleAttributeName
                      value:@(NSUnderlineStyleSingle)
                      range:(NSRange){0,[tncString length]}];
    //此时如果设置字体颜色要这样
    [tncString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0,[tncString length])];
    
    //设置下划线颜色...
    [tncString addAttribute:NSUnderlineColorAttributeName value:lineColor?:color range:(NSRange){0,[tncString length]}];
    return tncString;
}

//判断是否为整形：
+ (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形：

+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

/**
 *
 *  判断用户输入的密码是否符合规范，符合规范的密码要求：
 1. 长度大于8位
 2. 密码中必须同时包含数字和字母
 */
+(BOOL)judgePassWordLegal:(NSString *)pass
{
    BOOL result = NO;
    // 判断长度大于8位后再接着判断是否同时包含数字和字符
    NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    result = [pred evaluateWithObject:pass];
    return result;
}

// 设置圆形图片
+ (void) setImageViewBorder:(UIImageView*)faceImageView
{
    
    faceImageView.layer.masksToBounds=YES;
    faceImageView.layer.cornerRadius=faceImageView.frame.size.width/2;
    [faceImageView.layer setBorderWidth:1];
    faceImageView.layer.borderColor=[UIColor colorWithHexString:MAIN_BACK_COLOR].CGColor;
    faceImageView.contentMode=UIViewContentModeScaleAspectFill;
    
}

#pragma mark - UILabel自适应

+(CGSize)sizeFitForContent:(NSString *)content withSize:(CGSize)size withFont:(UIFont *)font
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
    CGSize actualSize = [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return actualSize;
}


+ (NSDictionary *)queryParams:(NSString *)url {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *param in [url componentsSeparatedByString:@"&"]) {
        NSArray *elts = [param componentsSeparatedByString:@"="];
        if([elts count] < 2) continue;
        [params setObject:elts[1] forKey:elts[0]];
    }
    return params;
}



+ (CGFloat)getKuai3Ratio {
    if(IS_IPHONE_6_LATER)
    {
       return 1.44f;
    }
    return 1.0f;
}

//把图片和微信一样压缩到200KB，小于200KB的不压缩
+ (NSData *)getCompressedImage:(UIImage *)originImage {
    
    CGFloat compression = 1.0f;
    CGFloat maxCompression = 0.1f;
    int maxFileSize = 200*1024;//200KB
    
    NSData *imageData = UIImageJPEGRepresentation(originImage, compression);
    
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(originImage, compression);
    }
    return imageData;
}


void openSMS(NSString * number)
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"sms://%@",number]]];
}

void openUrl(NSString *str)
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

void openCall(NSString *phoneNumber)
{
    phoneNumber= [phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
}

void openEmail(NSString *email)
{
    [[UIApplication sharedApplication ]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto://%@",email]]];
}

void gotoAppStore(NSString *appid)
{
    NSString * url = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?mt=8",appid];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

void gotoTouchID()
{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if([[UIApplication sharedApplication] canOpenURL:url]) {
        NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
        //此处可以做一下版本适配，至于为何要做版本适配，大家应该很清楚
        [[UIApplication sharedApplication] openURL:url];
    }
}

BOOL isAllowedNotification(){
    //iOS8 check if user allow notification
//    if ([getVersion() integerValue]>=8.0) {// system is iOS8
//    } else {//iOS7
//        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
//        if(UIRemoteNotificationTypeNone != type)
//            return YES;
//    }
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    if (UIUserNotificationTypeNone != setting.types) {
        return YES;
    }
    
    return NO;
}

void showMessageAutoMiss(NSString *message)
{
    if (!message.length) return;
    
    if([[NSThread currentThread] isMainThread])
    {
        [LTX_Common showAlertWithMessageup:message];
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [LTX_Common showAlertWithMessageup:message];
        });
    }
    
}

void showAnimationAutoMiss(UIView *view)
{
    if([[NSThread currentThread] isMainThread])
    {
        [LTX_Common showAnimationWithView:view];
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [LTX_Common showAnimationWithView:view];
        });
    }
}

BOOL wlwUserPhotoDenied(){
    ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
    BOOL a = (authStatus==ALAuthorizationStatusRestricted || authStatus==ALAuthorizationStatusDenied);
    if (a) {
        NSString* appName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
        NSString* message = [NSString stringWithFormat:@"请在iPhone“设置-隐私-相机”选项中，允许%@访问你的照片库。", appName];
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil
                                              cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert show];
    }
    return a;
}

NSString * getVersion(){
    return [[UIDevice currentDevice] systemVersion];
}

NSString * getDeviceName(){
    return [[UIDevice currentDevice] model];
}
//获得设备型号
NSString * getCurrentDeviceModel()
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceString isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([deviceString isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([deviceString isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([deviceString isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([deviceString isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([deviceString isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([deviceString isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([deviceString isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([deviceString isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([deviceString isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([deviceString isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([deviceString isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([deviceString isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([deviceString isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([deviceString isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    if ([deviceString isEqualToString:@"iPhone8,1"])   return @"iPhone 6S";
    if ([deviceString isEqualToString:@"iPhone8,2"])   return @"iPhone 6S Plus";
    if ([deviceString isEqualToString:@"iPhone8,4"])   return @"iPhone SE";
    if ([deviceString isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    if ([deviceString isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if ([deviceString isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([deviceString isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([deviceString isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([deviceString isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([deviceString isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([deviceString isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    
    if ([deviceString isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([deviceString isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([deviceString isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([deviceString isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([deviceString isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([deviceString isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([deviceString isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([deviceString isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([deviceString isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([deviceString isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([deviceString isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([deviceString isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([deviceString isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([deviceString isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([deviceString isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([deviceString isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([deviceString isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([deviceString isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([deviceString isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    
    if ([deviceString isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([deviceString isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    return deviceString;
    
}

+ (UIViewController *)getCurrentVC {
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}



+ (UIImage*)getCaptureWithTableView:(UITableView *)tableView
{
    
    UIImage* viewImage = nil;
    UITableView *scrollView = tableView;
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(floor(scrollView.contentSize.width), floor(scrollView.contentSize.height)-110), scrollView.opaque, 0.0);
    {
        CGPoint savedContentOffset = scrollView.contentOffset;
        
        CGRect savedFrame = scrollView.frame;
        
        scrollView.contentOffset = CGPointZero;
        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
        
        [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        viewImage = UIGraphicsGetImageFromCurrentImageContext();
        
        scrollView.contentOffset = savedContentOffset;
        scrollView.frame = savedFrame;
    }
    UIGraphicsEndImageContext();
    
    return viewImage;
}

+(UIImage*) captureView:(UIView *)theView {
    CGRect rect = theView.frame;
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(floor(rect.size.width), floor(rect.size.height)), NO, [UIScreen mainScreen].scale);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+ (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 {

    CGSize size = CGSizeMake(MAX(floor(image1.size.width), floor(image2.size.width)), floor(image2.size.height + image1.size.height));
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);

    // Draw image1
    [image1 drawInRect:CGRectMake(0, 0, MAX(floor(image1.size.width), floor(image2.size.width)), floor(image1.size.height))];
    // Draw image2
    [image2 drawInRect:CGRectMake(0, floor(image1.size.height),MAX(floor(image1.size.width), floor(image2.size.width)), floor(image2.size.height))];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

+ (UIImage *)addLfetImage:(UIImage *)image1 rightImage:(UIImage *)image2 {
    
    CGSize size = CGSizeMake(floor(image2.size.width + image1.size.width), MAX(floor(image1.size.height), floor(image2.size.height)));
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    // Draw image1
    [image1 drawInRect:CGRectMake(0, 0, floor(image1.size.width), MAX(floor(image1.size.height), floor(image2.size.height)))];
    // Draw image2
    [image2 drawInRect:CGRectMake(floor(image1.size.width), 0,floor(image2.size.width), MAX(floor(image1.size.height), floor(image2.size.height)))];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

+ (UIImage *)captureHalfViewWith:(UIImageView *)view
{
    [view sizeToFit];
    CGSize imgSize = CGSizeMake(floor(view.size.width), floor(view.size.height));
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(floor(imgSize.width),floor(imgSize.height/2)), NO, [UIScreen mainScreen].scale);

    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}




+(NSString *)convertToJsonData:(NSDictionary *)dict
{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}


+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


+ (NSDate*)toDateWith:(NSString*)str {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:str];
    return date;
}



+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    NSCalendar *calendar = [NSCalendar currentCalendar];//[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];//[[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    return [weekdays objectAtIndex:theComponents.weekday];
}




+ (void)playSound:(NSString*)soundName {
    
    NSString *urlString = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"]];
    SystemSoundID soundID = 0;
    if (soundID == 0)
    {
        NSURL *url = [NSURL URLWithString:urlString];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)url, &soundID);
    }
    
    AudioServicesPlaySystemSound(soundID);
}



+ (void)playVibrate {
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}


//改变label字间距
+ (void)changeWordSpaceForLabel:(UILabel *)label WithSpace:(float)space {
    
    NSString *labelText = label.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(space)}];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    label.attributedText = attributedString;
    [label sizeToFit];
    
}

+ (void)animationSubViewWithCurrenSubViews:(NSArray *)subviews completion:(void (^)(void))completion
{
    CGFloat timeRadix = 0.15;
    for (NSInteger i = 0; i<subviews.count; i++) {
        UIView *subView = subviews[i];
        subView.transform = CGAffineTransformMakeTranslation(ScreenW, 0);
        
        [UIView animateWithDuration:timeRadix * i + timeRadix animations:^{
            
            subView.transform = CGAffineTransformMakeTranslation(- 5, 0);
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.05 animations:^{
                subView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                if (completion) {
                    completion();
                }
            }];
        }];
    }

}


+ (void)animationLeftSubViewWithCurrenSubViews:(NSArray *)subviews completion:(void (^)(void))completion
{
    CGFloat timeRadix = 0.15;
    for (NSInteger i = 0; i<subviews.count; i++) {
        UIView *subView = subviews[i];
        subView.transform = CGAffineTransformMakeTranslation(-ScreenW, 0);
        
        [UIView animateWithDuration:timeRadix * i + timeRadix animations:^{
            
            subView.transform = CGAffineTransformMakeTranslation(5, 0);
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.05 animations:^{
                subView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                
                if (completion) {
                    completion();
                }
            }];
        }];
    }
}

+ (void)disMissAnimationSubViewWithCurrenSubViews:(NSArray *)subviews completion:(void (^)(void))completion
{
    CGFloat timeRadix = 0.1;
    for (NSInteger i = 0; i<subviews.count; i++) {
        UIView *subView = subviews[i];
        
//        subView.transform = CGAffineTransformIdentity;
        
        [UIView animateWithDuration:0.05 animations:^{
            
            subView.transform = CGAffineTransformMakeTranslation(5, 0);
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:timeRadix * i + timeRadix animations:^{
                subView.transform = CGAffineTransformMakeTranslation(-ScreenW, 0);
            } completion:^(BOOL finished) {
                
                if (completion) {
                    completion();
                }
            }];
        }];
    }
}

+ (void)disMissRightAnimationSubViewWithCurrenSubViews:(NSArray *)subviews completion:(void (^)(void))completion
{
    CGFloat timeRadix = 0.1;
    for (NSInteger i = 0; i<subviews.count; i++) {
        UIView *subView = subviews[i];
//        subView.transform = CGAffineTransformIdentity;
        
        [UIView animateWithDuration:0.05 animations:^{
            
            subView.transform = CGAffineTransformMakeTranslation(- 5, 0);
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:timeRadix * i + timeRadix animations:^{
                subView.transform = CGAffineTransformMakeTranslation(ScreenW, 0);
            } completion:^(BOOL finished) {
                
                if (completion) {
                    completion();
                }
            }];
        }];
    }
}


/**
 开启一个定时器
 
 @param target 定时器持有者
 @param timeInterval 执行间隔时间
 @param handler 重复执行事件
 */
void dispatchTimer(id target, double timeInterval,void (^handler)(dispatch_source_t timer))
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), (uint64_t)(timeInterval *NSEC_PER_SEC), 0);
    // 设置回调
    __weak __typeof(target) weaktarget  = target;
    dispatch_source_set_event_handler(timer, ^{
        if (!weaktarget)  {
            dispatch_source_cancel(timer);
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (handler) handler(timer);
            });
        }
    });
    // 启动定时器
    dispatch_resume(timer);
}

+(int) lBytesToInt:(Byte[]) byte
{
    int height = 0;
    NSData * testData =[NSData dataWithBytes:byte length:4];
    for (int i = 0; i < [testData length]; i++)
    {
        if (byte[[testData length]-i] >= 0)
        {
            height = height + byte[[testData length]-i];
        } else
        {
            height = height + 256 + byte[[testData length]-i];
        }
        height = height * 256;
    }
    if (byte[0] >= 0)
    {
        height = height + byte[0];
    } else {
        height = height + 256 + byte[0];
    }
    return height;
}

+ (NSString*)iphoneType {
    
    //需要导入头文件：#import <sys/utsname.h>
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    
    if([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if([platform isEqualToString:@"iPhone10,1"]) return @"iPhone 8";
    
    if([platform isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    
    if([platform isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
    
    if([platform isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    
    if([platform isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    
    if([platform isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    
//    if([platform isEqualToString:@"iPod1,1"])  return @"iPod Touch 1G";
//
//    if([platform isEqualToString:@"iPod2,1"])  return @"iPod Touch 2G";
//
//    if([platform isEqualToString:@"iPod3,1"])  return @"iPod Touch 3G";
//
//    if([platform isEqualToString:@"iPod4,1"])  return @"iPod Touch 4G";
//
//    if([platform isEqualToString:@"iPod5,1"])  return @"iPod Touch 5G";
//
//    if([platform isEqualToString:@"iPad1,1"])  return @"iPad 1G";
//
//    if([platform isEqualToString:@"iPad2,1"])  return @"iPad 2";
//
//    if([platform isEqualToString:@"iPad2,2"])  return @"iPad 2";
//
//    if([platform isEqualToString:@"iPad2,3"])  return @"iPad 2";
//
//    if([platform isEqualToString:@"iPad2,4"])  return @"iPad 2";
//
//    if([platform isEqualToString:@"iPad2,5"])  return @"iPad Mini 1G";
//
//    if([platform isEqualToString:@"iPad2,6"])  return @"iPad Mini 1G";
//
//    if([platform isEqualToString:@"iPad2,7"])  return @"iPad Mini 1G";
//
//    if([platform isEqualToString:@"iPad3,1"])  return @"iPad 3";
//
//    if([platform isEqualToString:@"iPad3,2"])  return @"iPad 3";
//
//    if([platform isEqualToString:@"iPad3,3"])  return @"iPad 3";
//
//    if([platform isEqualToString:@"iPad3,4"])  return @"iPad 4";
//
//    if([platform isEqualToString:@"iPad3,5"])  return @"iPad 4";
//
//    if([platform isEqualToString:@"iPad3,6"])  return @"iPad 4";
//
//    if([platform isEqualToString:@"iPad4,1"])  return @"iPad Air";
//
//    if([platform isEqualToString:@"iPad4,2"])  return @"iPad Air";
//
//    if([platform isEqualToString:@"iPad4,3"])  return @"iPad Air";
//
//    if([platform isEqualToString:@"iPad4,4"])  return @"iPad Mini 2G";
//
//    if([platform isEqualToString:@"iPad4,5"])  return @"iPad Mini 2G";
//
//    if([platform isEqualToString:@"iPad4,6"])  return @"iPad Mini 2G";
//
//    if([platform isEqualToString:@"iPad4,7"])  return @"iPad Mini 3";
//
//    if([platform isEqualToString:@"iPad4,8"])  return @"iPad Mini 3";
//
//    if([platform isEqualToString:@"iPad4,9"])  return @"iPad Mini 3";
//
//    if([platform isEqualToString:@"iPad5,1"])  return @"iPad Mini 4";
//
//    if([platform isEqualToString:@"iPad5,2"])  return @"iPad Mini 4";
//
//    if([platform isEqualToString:@"iPad5,3"])  return @"iPad Air 2";
//
//    if([platform isEqualToString:@"iPad5,4"])  return @"iPad Air 2";
//
//    if([platform isEqualToString:@"iPad6,3"])  return @"iPad Pro 9.7";
//
//    if([platform isEqualToString:@"iPad6,4"])  return @"iPad Pro 9.7";
//
//    if([platform isEqualToString:@"iPad6,7"])  return @"iPad Pro 12.9";
//
//    if([platform isEqualToString:@"iPad6,8"])  return @"iPad Pro12.9";
//
//    if([platform isEqualToString:@"i386"])  return @"iPhone Simulator";
//
//    if([platform isEqualToString:@"x86_64"])  return @"iPhone Simulator";
    
    return platform;
    
}

+ (NSData*)getJSON:(id)obj options:(NSJSONWritingOptions)options error:(NSError**)error
{
    return [NSJSONSerialization dataWithJSONObject:[self getObjectData:obj]options:options error:error];
}

+ (id)getObjectInternal:(id)obj
{
    if([obj isKindOfClass:[NSString class]]
       || [obj isKindOfClass:[NSNumber class]]
       || [obj isKindOfClass:[NSNull class]])
    {
        return obj;
    }
    
    if([obj isKindOfClass:[NSArray class]])
    {
        NSArray *objarr = obj;
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        for(int i =0;i < objarr.count; i++)
        {
            [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]]atIndexedSubscript:i];
        }
        return arr;
    }
    
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *objdic = obj;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        for(NSString *key in objdic.allKeys)
        {
            [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
        }
        return dic;
    }
    return [self getObjectData:obj];
}

+ (NSDictionary*)getObjectData:(id)obj
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int propsCount;
    objc_property_t *props =class_copyPropertyList([obj class], &propsCount);
    for(int i =0;i < propsCount; i++)
    {
        objc_property_t prop = props[i];
        
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
        id value = [obj valueForKey:propName];
        if(value ==nil)
        {
            value = [NSNull null];
        }
        else
        {
            value = [self getObjectInternal:value];
        }
        [dic setObject:value forKey:propName];
    }
    return dic;
}

+ (NSString *)getPeriodOfNowTime
{
    
    NSDate * nowDate = [NSDate date];
    NSCalendarUnit components = (NSCalendarUnit)(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitHour | NSCalendarUnitMinute);
    NSDateComponents *nowDateComponents = [[NSCalendar currentCalendar] components:components fromDate:nowDate];
    NSInteger hour = nowDateComponents.hour;
    NSInteger minute = nowDateComponents.minute;
    NSInteger totalMin = hour *60 + minute;
    NSString *showPeriodOfTime = @"";
    
    if (totalMin > 0 && totalMin <= 5 * 60) {
        showPeriodOfTime = Multilingual(@"凌晨好");
    } else if (totalMin > 5 * 60 && totalMin < 12 * 60) {
        showPeriodOfTime = Multilingual(@"上午好");
    } else if (totalMin >= 12 * 60 && totalMin <= 18 * 60) {
        showPeriodOfTime = Multilingual(@"下午好");
    } else if ((totalMin > 18 * 60 && totalMin <= (23 * 60 + 59)) || totalMin == 0) {
        showPeriodOfTime = Multilingual(@"晚上好");
    }
    return showPeriodOfTime;
}

+ (UIImage *)createQrCodeWithContent:(NSString *)content andWidth:(CGFloat)size
{
    //创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //过滤器恢复默认
    [filter setDefaults];
    //给过滤器添加数据
    NSString *string = content;
    //将NSString格式转化成NSData格式
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    [filter setValue:data forKeyPath:@"inputMessage"];
    //获取二维码过滤器生成的二维码
    CIImage *image = [filter outputImage];
    //将获取到的二维码添加到imageview上
    return [self createNonInterpolatedUIImageFormCIImage:image withSize:size];
}
/**
*  根据CIImage生成指定大小的UIImage
*
*  @param image CIImage
*  @param size  图片宽度
*/
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}
@end
